<template>
  <div class="location w100 h100">
    <div class="search">
      <span>设备类型</span>
      <el-select v-model="devname" placeholder="请选择" slot="append">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </div>
    <!-- 上方盒子 -->
    <right-box :devname='devname'></right-box>
    <!-- 左侧地图 -->
    <div class="map">
      <div style="height:20px;margin:0 0 12px 0">
        <img src="../../../../../static/image/ShowMap/state.png" style="float:left;margin:0 8px">
        <span class="font">设备状态分布</span>
      </div>

      <!-- 地图 -->
      <div id="allmap"></div>
      <!-- 地图右上角按钮 -->
      <show-box @state_change="state_change" :devname='devname'></show-box>
    </div>
  </div>
</template>

<script>
import Config from '../../../../config'
import RightBox from './RightBox'
import ShowBox from './ShowBox'
import location from '../../../../util/location'
// import { regionData } from 'element-china-area-data'
import { regionData } from 'static/js/regionData'
export default {
  name: 'Location',
  components: {
    RightBox,
    // LeftSearch,
    ShowBox
  },
  data: function () {
    return {
      options: [{
        value: '',
        label: '全部'
      },
      {
        value: 'fireplug',
        label: '消防栓'
      }, {
        value: 'scm',
        label: '烟感设备'
      }],
      devname: '',
      // 地图实例
      map: null,
      // 两种类型点数据

      blue: [],
      red: [],
      // 弹框
      infoBox: '',
      infoBoxTemp: null,
      img: ''
    }
  },
  watch: {
    '$store.state.user.district.city_name'(data) {
      this.ready(data)
    },
    devname(data) {
      this.stops()
    }
  },
  methods: {
    ready(city) {
      // 百度地图API功能
      let map = new BMap.Map("allmap", { enableMapClick: false }) // 创建Map实例
      this.map = map

      console.log('city ', city)

      if (city === '直辖县') {
        city = '济源市'
      }

      let bdary = new BMap.Boundary()
      bdary.get(city, (rs) => {      //获取行政区域
        let count = rs.boundaries.length //行政区域的点有多少个
        if (count === 0) {
          map.centerAndZoom(new BMap.Point(116.404, 39.915), 11)
          this.$notify({
            title: '警告',
            message: '未能获取当前行政区域',
            type: 'warning'
          })
        } else {
          let pointArray = []
          for (let i = 0; i < count; i++) {
            let ply = new BMap.Polygon(rs.boundaries[i], { strokeWeight: 2, strokeColor: "#ff0000" }) //建立多边形覆盖物
            // map.addOverlay(ply) //添加覆盖物
            pointArray = pointArray.concat(ply.getPath())
          }
          map.setViewport(pointArray)   //调整视野
          // 获取点
          this.stops()
          // 地图点击事件
          map.addEventListener("click", (e) => {
            this.click(e)
          })
        }
      })
      // 比例尺
      map.addEventListener("load", (e) => {
        map.addControl(new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT }))
      })
      map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放

    },
    // 获取数据
    stops() {
      let url = `${Config.DEVICE_MANAGE_URL}/device_equip_site/query_for_map`
      let param = null

      if (this.$store.state.user.district.areaCode) {
        param = {
          devtype: Config.objType.devtype,
          devname: this.devname,
          id: this.$store.state.user.district.districtId
        }
      } else if (this.$store.state.user.district.cityCode) {
        param = {
          devtype: Config.objType.devtype,
          devname: this.devname,
          city: this.$store.state.user.district.cityCode
        }
      } else if (this.$store.state.user.district.provinceCode) {
        param = {
          devtype: Config.objType.devtype,
          devname: this.devname,
          province: this.$store.state.user.district.provinceCode
        }
      } else {
        param = {
          devtype: Config.objType.devtype,
          devname: this.devname,
          city: this.$store.state.user.district.city[this.$store.state.user.district.city.length - 1]
        }
      }
      // 判断权限 test//神//凡人
      if (this.$store.state.user.role[0].sort === 93) {
        param.site_type = 'test'
      } else if (this.$store.state.user.role[0].sort !== 100) {
        param.site_type = 'official'
      }
      // 处理空对象
      for (let i in param) {
        if (param[i] == "" || param[i] == null) {
          param[i] = undefined;
          // console.log(this.formR[i])
        }
      }
      this.$http.get(url, param).then((res) => {
        this.map.clearOverlays() // 清空数据
        // 处理的数据
        this.blue = []
        this.red = []
        res.array.map((item, i) => {
          let obj = {}
          // obj = location.gpsChange(item[3], item[4]) // 转换后的经纬度
          obj.point = new BMap.Point(item[3], item[4]) // 经纬度
          obj.id = item[0] // id
          obj.name = item[1] // 场所名称
          obj.number = item[5] // 安装数量
          obj.on_line = item[6] // 在线数量
          obj.normal = item[7] // 正常数量
          obj.fireplug = item[8] // 消防
          obj.scm = item[9] // 烟感

          // 判断红蓝
          if (obj.number === obj.on_line && obj.number === obj.normal) {
            this.blue.push(obj)
          } else {
            this.red.push(obj)
          }
        })
        this.drawing(this.blue, 'blue')
        this.drawing(this.red, 'red')
      })
      // 随机向地图添加25个标注

      // let bounds = this.map.getBounds();
      // let sw = bounds.getSouthWest();
      // let ne = bounds.getNorthEast();
      // let lngSpan = Math.abs(sw.lng - ne.lng);
      // let latSpan = Math.abs(ne.lat - sw.lat);

      // for (let i = 0; i < 10; i ++) {
      //   let point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7));
      //   this.blue.push(point)
      // }
      // for (let i = 0; i < 10; i ++) {
      //   let point = new BMap.Point(sw.lng + lngSpan * (Math.random() * 0.7), ne.lat - latSpan * (Math.random() * 0.7));
      //   this.red.push(point)
      // }

      // this.drawing(this.blue, 'blue')
      // this.drawing(this.red, 'red')
    },
    // 绘制点
    drawing(data, status) {
      let icon
      data.map((item) => {
        if (status === 'blue') {
          // 共存
          if (item.fireplug && item.scm) {
            icon = new BMap.Icon("../../../../../static/image/ShowMap/BAll.png", new BMap.Size(39, 39))
            item.name = '消防和烟感'
          }
          // 消防
          if (item.fireplug && !item.scm) {
            icon = new BMap.Icon("../../../../../static/image/ShowMap/BF.png", new BMap.Size(39, 39))
            item.name = '消防'
          }
          // 烟雾
          if (!item.fireplug && item.scm) {
            icon = new BMap.Icon("../../../../../static/image/ShowMap/BC.png", new BMap.Size(39, 39))
            item.name = '烟感'
          }
        } else {
          // 共存
          if (item.fireplug && item.scm) {
            icon = new BMap.Icon("../../../../../static/image/ShowMap/RAll.png", new BMap.Size(39, 39))
            item.name = '消防和烟感'
          }
          // 消防
          if (item.fireplug && !item.scm) {
            icon = new BMap.Icon("../../../../../static/image/ShowMap/RF.png", new BMap.Size(39, 39))
            item.name = '消防'
          }
          // 烟雾
          if (!item.fireplug && item.scm) {
            icon = new BMap.Icon("../../../../../static/image/ShowMap/RC.png", new BMap.Size(39, 39))
            item.name = '烟感'
          }
        }


        // 画点
        const pt = item.point
        const marker = new BMap.Marker(pt, { icon })
        marker.item = item
        this.map.addOverlay(marker)


        // 点击点
        marker.addEventListener('click', () => {
          this.typeClick(marker)
          // 点击相应点 动画平移到中间
          setTimeout(() => {
            this.map.panTo(marker.getPosition())
          }, 20)
        })
      })
    },
    // 弹框
    typeClick(marker) {
      // 禁止重复弹框
      if (this.infoBox) {
        this.infoBox.close()
      }
      this.typedata(marker)

    },
    // 请求弹框数据
    typedata(marker) {
      console.log(this.devname)
      let url = `${Config.FIREPLUG_APP_URL}/fireplug/count`;
      let param = {
        site_id: marker.item.id,
        devname: this.devname?this.devname:undefined
      }
      // 获取弹框数据
      this.$http.post(url, param).then((res) => {
        // 正常设备数量
        let normal = res.total - res.exception
        var html = ["<div style='margin: 12px 23px 16px 16px; color: #EB3838; font-size: 14px;'><span style='font-weight: bold;'>设备状态</span><span style='float: right;'><a href='#/show/location/" +this.devname+ ','+ marker.item.id + "' style='text-decoration: none;color: #EB3838;font-size: 12px;'>详情 <img src='../../../../../static/image/ShowMap/right.png'></a></span></div>" +
          "<div style='margin: 0px 16px 8px 16px; color: #333333; font-weight: bold; font-size: 12px;'>设备类型：   <span style='color:#666666;font-weight: 400;'>" + marker.item.name + "</span></div>" +
          "<div style='margin: 0px 16px 8px 16px; color: #333333; font-weight: bold; font-size: 12px;'>异常设备：   <span style='color:#666666;font-weight: 400;'>" + res.exception + "台</span></div>" +
          "<div style='margin: 0px 16px 0px 16px; color: #333333; font-weight: bold; font-size: 12px;'>正常设备：   <span style='color:#666666;font-weight: 400;'>" + normal + "台</span></div>"]
        this.infoBox = new BMapLib.InfoBox(this.map, html, {
          boxStyle: {
            background: "url('../../../../../static/image/ShowMap/backimg.png') no-repeat center top",
            width: "200px",
            height: "136px"
          },
          offset: new BMap.Size(0, 20),
          closeIconMargin: "130px 92px 0 0",
          closeIconUrl: '../../../../../static/image/ShowMap/1px.png',
          enableAutoPan: false,
          align: INFOBOX_AT_TOP
        })
        this.infoBox.open(marker) // 打开弹框
      }).catch(function (error) {
        // console.log(error)
      })
    },
    // 点击地图
    click(e) {
      if(!e.overlay){
        if (this.infoBox) {
          this.infoBox.close()
          this.infoBox = null
        }
      }
      let bs = this.map.getBounds() // 获取可视区域
      let bssw = bs.getSouthWest() // 可视区域左下角
      let bsne = bs.getNorthEast() // 可视区域右上角
      console.log(location.Convert_BD09_To_GCJ02(bssw.lat, bssw.lng), location.Convert_BD09_To_GCJ02(bsne.lat, bsne.lng))
    },

    // 点击状态改变
    state_change(data) {
      // 清除覆盖物
      this.map.clearOverlays()
      switch (data) {
        case 0:
          this.drawing(this.blue, 'blue')
          this.drawing(this.red, 'red')
          break
        case 1:
          this.drawing(this.blue, 'blue')
          break
        case 2:
          this.drawing(this.red, 'red')
          break
      }
    },
  },
  computed: {
  },
  mounted() {
    let obj = this.$store.state.user.district
    // 如果是场所用户地图展现到场所
    if (obj.areaCode) {

      regionData.map((provinceCode) => {
        if (provinceCode.value === obj.provinceCode) {
          provinceCode.children.map((cityCode) => {
            if (cityCode.value === obj.cityCode) {
              // if (!cityCode.children) {
              //   this.ready(provinceCode.label + cityCode.label)
              //   return
              // }
              cityCode.children.map((areaCode) => {
                if (areaCode.value === obj.areaCode) {
                  this.ready(provinceCode.label + areaCode.label)
                  // console.log(provinceCode.label + areaCode.label)
                }
              })
            }
          })
        }
      })
    } else if (obj.city_name) {
      this.ready(obj.city_name)
    }
  }
}
</script>
<style lang="scss">
@import "../../../../../static/scss/common";
.location {
  // 上方搜索
  .search {
    height: 32px;
    width: 180px;
    display: inline-block;
    background: #fff;
    margin-bottom: 12px;
    text-align: center;
    line-height: 32px;
    > span {
      font-size: 14px;
      color: #333;
      position: relative;
    }
    > span::before {
      position: absolute;
      display: block;
      right: -8px;
      top: 3px;
      content: " ";
      width: 1px;
      height: 16px;
      background: #f0f0f0;
      z-index: 1;
    }
    .el-select {
      width: 104px;
      .el-input--suffix {
        .el-input__inner {
          border: 0;
          border-radius: 0;
          color: #333;
        }
        .el-input__suffix {
          .el-input__suffix-inner {
            .el-input__icon {
              line-height: 32px;
              width: 15px;
            }
          }
        }
      }
    }
  }

  // 左侧地图
  .map {
    width: 100%;
    height: 740px;
    background: $white;
    box-sizing: border-box;
    padding: 12px;
    float: left;
    position: relative;
    margin: 24px 0 24px;

    .font {
      color: $gray3;
      font-size: 16px;
      font-weight: bold;
    }
    // 地图
    #allmap {
      width: 100%;
      height: calc(100% - 32px);
    }
  }
}
</style>
